package com.iot.gateway.utils.serializer;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

public class XmlSerializer<T> implements DataSerializer<T> {

    @Override
    public String serialize(T data) throws Exception {
        // 创建 DocumentBuilder
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        // 创建根元素
        Element root = document.createElement("Data");
        document.appendChild(root);
        // 遍历对象字段并生成 XML 元素
        for (java.lang.reflect.Field field : data.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(data);
            Element element = document.createElement(field.getName());
            element.appendChild(document.createTextNode(value != null ? value.toString() : ""));
            root.appendChild(element);
        }
        // 转换为 XML 字符串
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        return writer.toString();
    }

}
